<template>
  <div class="app-container">
    <!-- <mainTilte title="配件管理" /> -->
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />

    <!-- <div class="filters-wrap clearfix mb24">
      <div class="filters-area">
        <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
          <el-select v-model.trim="searchParams.type" clearable placeholder="编码">
            <el-option v-for="(item, index) of issignContract" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-col>
        <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
          <el-input v-model.trim="searchParams.value" placeholder="关键字回车搜索" @keyup.enter.native="handleSearch" />
        </el-col>
        <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
          <product-category v-model="searchParams.category_id" @change="handleSearch" />
        </el-col>
        <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
          <el-select v-model="searchParams.flow_to" placeholder="流向" @change="handleSearch">
            <el-option label="国内" :value="1" />
            <el-option label="国外" :value="2" />
          </el-select>
        </el-col>
      </div>
    </div> -->
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'parts@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="add">新增配件</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button v-action="'parts@disable'" size="small" type="primary" @click="stopClick">禁用</el-button>
        <el-button v-action="'parts@enable'" size="small" type="primary" @click="startClick">启用</el-button>
        <el-button v-action="'parts@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出配件</el-button>
        <el-button v-action="'parts@importPart'" size="small" type="primary" :loading="exportLoading" @click="handleImport">导入配件</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        <el-button size="small" @click="isActive=!isActive">{{ isActive?'展开':'收起' }}</el-button>
      </div>
    </div>
    <div v-loading="loading" class="page-grid">

      <egrid :screen-heigh="screenHeigh" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中o..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
      <epagination v-if="tableData" :total="total" :current="queryParam.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <down-modul :form-visible-down.sync="formVisibleDown" :url="downUrl" :search-param="searchParamObj" :options-modul="downModulOptions" />
    <!-- 导出 -->
    <!-- <down-modul
      url="/products/export"
      :search-param="searchParamsObj"
      :form-visible-down.sync="formVisibleDown"
      :options-modul="downModulOptions"
    /> -->
    <!-- 导入 -->
    <import-dialog url="/part/importPart" title="配件导入" :form-visible.sync="importDialogVisible" @download="downLoad" @handleRefresh="handleRefresh" />
  </div>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import thund from '@/components/base/thund'
import dicValues from '@/components/dicTransform/index'
import codeItem from '@/components/base/code'
import DownModul from '@/components/DownModul/index'
import { action } from '@/directive/permission/index.js' // 权限判断指令
// import { downloadxlsx } from '@/utils/index'
import cacheList from '@/layout/mixin/cacheList'
import { downloadStream } from '@/utils/index'
import importDialog from '@/components/importDialog/index'
export default {
  name: 'AccessoriesManage',
  components: { DownModul, importDialog },
  directives: {
    action
  },
  mixins: [formOperate, list, cacheList],
  data() {
    const DICTIONARIES = {
      // 状态 2-禁用 1-启用
      isableList: [
        {
          code: 1,
          name: '启用'
        },
        {
          code: 2,
          name: '禁用'
        }
      ],
      flwList: [
        {
          name: '国内',
          code: 1
        },
        {
          name: '国外',
          code: 2
        }
      ]
    }
    return {
      importDialogVisible: false,
      otherHeight: 390,
      isActive: false,
      formVisibleDown: false, // 导出弹窗 显示
      downModulOptions: [{
        'label': '产品图片',
        'key': 'image_url'
      },
      {
        'label': '所属分类',
        'key': 'category_name_text'
      },
      {
        'label': '配件编码',
        'key': 'code'
      },
      {
        'label': '配件名称',
        'key': 'name_ch'
      },
      {
        'label': '配件流向',
        'key': 'flow_to_text'
      },
      // {
      //   'label': '所属供应商',
      //   'key': 'supplier_name'
      // },
      {
        'label': '采购员',
        'key': 'purchase_name'
      },
      {
        'label': '邮购包装尺寸',
        'key': 'size_mailing'
      },
      {
        'label': '体积',
        'key': 'volume'
      },
      {
        'label': '美制毛重',
        'key': 'weight_gross_AS'
      },
      {
        'label': '外箱箱率',
        'key': 'box_rate'
      },
      {
        'label': '适用商品',
        'key': 'product_names'
      }
      ],
      componentName: 'AccessoriesManage',
      classifyList: [],
      propsClassify: {
        disabled: 'disabled' // 商品分类只能选择二级
      },
      /** *
       * 定义搜索框
       */
      searchClass: 1,
      queryParam: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        type: '',
        value: '',
        category_id: '',
        flow_to: '',
        name: '',
        code: '',
        supplier_name: '',
        purchase_name: ''
      },
      formItems: [
        {
          label: '配件编码',
          key: 'code',
          type: 'input',
          placeholder: '请输入编码'
        },
        {
          label: '配件名称',
          key: 'name',
          type: 'input',
          placeholder: '请输入名称'
        },
        {
          label: '采购员',
          key: 'purchase_name',
          type: 'input',
          placeholder: '请输入采购员'
        },
        // {
        //   // SupplierName
        //   label: '所属供应商',
        //   key: 'supplier_name',
        //   type: 'input',
        //   placeholder: '请输入所属供应商'
        // },
        // {
        //   label: '供应商',
        //   key: 'supplier_name',
        //   type: 'input',
        //   placeholder: '请输入供应商'
        // },
        {
          label: '所属分类',
          key: 'category_ids',
          type: 'cascader',
          cLabel: 'lable',
          cValue: 'value',
          options: []
        },
        {
          label: '流向',
          key: 'flow_to',
          type: 'select', // 1-国内 2-国外
          options: [
            {
              label: '国内',
              value: '1'
            },
            {
              label: '国外',
              value: '2'
            }
          ]
        }
      ],
      issignContract: [
        {
          name: '编码',
          code: 'code'
        },
        {
          name: '名称',
          code: 'name'
        },
        {
          name: '供应商',
          code: 'supplier_name'
        }
      ],

      columns: [
        {
          label: '缩略图',
          prop: 'image_url',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '配件编码',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '配件名称',
          prop: 'name_ch',
          width: '200',
          align: 'center',
          tooltip: false,
          component: codeItem,
          propsHandler: ({ row, col, column }) => {
            return {
              code: row.name_ch ? row.name_ch : '',
              routePath: '/product/accessoriesManage/accessoriesDetails',
              queryData: { id: row.id }
            }
          }
        },
        {
          label: '所属分类',
          prop: 'category_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '流向',
          prop: 'flow_to',
          width: 100,
          align: 'center',
          tooltip: false,
          component: dicValues,
          propsHandler({ row }) {
            return {
              code: row.flow_to,
              dictionaries: DICTIONARIES.flwList
            }
          }
        },
        // {
        //   label: '所属供应商',
        //   prop: 'supplier_name',
        //   width: 100,
        //   align: 'center',
        //   tooltip: false
        // },
        {
          label: '采购员',
          prop: 'purchase_name',
          width: 100,
          align: 'center',
          tooltip: false
        },
        {
          label: '状态',
          prop: 'is_status',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'creator_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '174',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'update_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '174',
          align: 'center',
          tooltip: false
        }
      ],
      columnsSchema: {
        缩略图: {
          propsHandler({ col, row }) {
            return {
              img: row.image_url
            }
          },
          component: thund
        },
        状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['isableList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      downVisible: false, // 导出 visible
      downUrl: '/parts/export', // 导出 url
      downOptions: [
        // 导出 options
        { key: 'id', label: 'ID' },
        { key: 'code', label: '订单编号' },
        { key: 'supplier_id', label: '供应商' },
        { key: 'is_status', label: '状态' },
        { key: 'flow_to', label: '流向' },
        { key: 'name_ch', label: '中文名称' },
        { key: 'purchase_name', label: '采购员' }
      ],
      exportLoading: false,
      cachePaths: [
        '/product/accessoriesManage/addAccessories',
        '/product/accessoriesManage/accessoriesDetails'
      ]
    }
  },
  computed: {
    searchParamObj({ issignContract }) {
      const vm = this
      const item = issignContract.find((e) => e.code === vm.queryParam.type)
      const params = {}
      if (item) {
        params[item.code] = vm.queryParam.value
      }
      params['category_id'] = vm.queryParam.category_id
      return params
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
    this.getTreeList()
  },
  activated() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
  },
  methods: {
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/part/template', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '配件导入模板.xlsx')
        })
    },
    // 导入
    handleImport() {
      const vm = this
      vm.importDialogVisible = true
    },
    beforeSearch() {
      const vm = this
      if (vm.queryParam.category_ids && vm.queryParam.category_ids.length > 0) {
        // vm.queryParam.category_id = vm.queryParam.category_ids.pop()
        const arr = vm.queryParam.category_ids
        vm.queryParam.category_id = arr[arr.length - 1]
      } else {
        vm.queryParam.category_id = ''
      }
    },
    handleSearch() {
      const vm = this
      vm.queryParam.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.queryParam.page = 1
      vm.queryParam.limit = 10
      vm.queryParam.type = ''
      vm.queryParam.value = ''
      vm.queryParam.category_id = ''
      vm.queryParam.category_ids = []
      vm.queryParam.flow_to = ''
      vm.queryParam.name = ''
      vm.queryParam.code = ''
      vm.queryParam.supplier_name = ''
      vm.queryParam.purchase_name = ''
      vm.query()
    },
    // 导出
    handleExport() {
      const vm = this
      vm.formVisibleDown = true
      //   vm.exportLoading = true
      //   const url = '/parts/export'
      //   const { type, value, category_id } = vm.queryParam
      //   const params = {
      //     category_id
      //   }
      //   if (type) {
      //     params[type] = value
      //   }
      //   vm.$http.post(url, params).then(res => {
      //     downloadxlsx(res.data)
      //     vm.exportLoading = false
      //   }).catch(() => {
      //     vm.exportLoading = false
      //   })
    },
    // 获取商品分类
    getTreeList() {
      const vm = this
      vm.$http.get(`/getListTree`).then(res => {
        const filter = (arr, parentIds = []) => {
          return arr.map(e => {
            e['value'] = e.id
            e['label'] = e.name
            // ids 用于 后续的 级联回填
            const ids = parentIds.concat()
            ids.push(e.id)
            e['ids'] = ids
            if (e.children) {
              e.children = filter(e.children, ids.concat())
            }
            return e
          })
        }
        const data = res.data.filter(e => e.children && e.children.length > 0)
        vm.classifyList = filter(data)
        vm.formItems = vm.formItems.map((arr) => {
          if (arr.key === 'category_ids') {
            arr.options = vm.classifyList
          }
          return arr
        })
        // vm.formItems[0].options = vm.classifyList
        vm.children = vm.classifyList.reduce((list, e) => {
          list = list.concat(e.children)
          return list
        }, [])
      })
    },
    handleChangeClassify(data) {
      this.queryParam.category_id = data[1]
      this.handleSearch()
    },
    // 点击搜索
    query() {
      const vm = this
      if (this.beforeSearch !== undefined) {
        this.beforeSearch()
      }
      let url = '/parts'
      const { page, limit, type, value, category_id, flow_to, name, code, supplier_name, purchase_name } = vm.queryParam // purchase_name
      url += `?page=${page}&limit=${limit}&category_id=${category_id}&flow_to=${flow_to}&purchase_name=${purchase_name}&name=${name}&code=${code}&supplier_name=${supplier_name}`
      if (type) {
        url += `&${type}=${value}`
      }
      this.initTableData(url)
    },
    // 新增
    add() {
      this.$router.push('/product/accessoriesManage/addAccessories')
    },
    // 禁用
    stopClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }
      vm.$confirm(`确定批量禁用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/parts/disable`, { ids: vm.ids })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('禁用成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    startClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }
      vm.$confirm(`确定批量启用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http.post(`/parts/enable`, { ids: vm.ids }).then((res) => {
          if (res.code === 10000) {
            vm.$message.success('启用成功')
            vm.query()
          }
        })
      })
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          const show = row.is_status !== 1
          return {
            row: row, // 信息
            edit: show,
            del: show,
            editAction: 'parts@update',
            delAction: 'parts@delete'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          deleteTableClick(row) {
            that
              .$confirm('您确定要删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.loading = true
                // 点击确定
                that.$http
                  .delete(`/parts/${row.id}`)
                  .then((res) => {
                    that.loading = false
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch(() => {
                    that.loading = false
                  })
              })
              .catch(() => {
                that.loading = false
              })
          },
          editTableClick(row) {
            that.$router.push({
              path: '/product/accessoriesManage/addAccessories',
              query: { title: '编辑配件', id: row.id }
            })
          }
        }
      })
    },
    handleSizeChange(val) {
      const vm = this
      vm.queryParam.limit = val
      vm.query()
    },
    handleCurrentChange(val) {
      this.queryParam.page = val
      this.query()
    }
  }
}
</script>

<style>
</style>
